extends CharacterBody3D

signal aim(multiple: float)

@export var mouse_sensitivity_multiple := 1.0
@export var multiple: float = 1.0 ## 相机FOV倍数
@export var max_hitpoints := 100 #生命值
@export var fall_multiple := 2.0 ##下落速度倍数
@export var jump_height := 1.0 ##跳跃高度
@onready var camera_pivot: Node3D = $CameraPivot
@onready var 动画_受到攻击: AnimationPlayer = $"DamageTexture/动画_受到攻击"
@onready var damage_texture: TextureRect = $DamageTexture
@onready var gameover: Control = $"Gameover"
@onready var ammo_manager: AmmoHandler = %AmmoManager

var SPEED := 5.0
var hitpoints := max_hitpoints:
	set(new_hitpoints):
		if new_hitpoints < hitpoints:
			动画_受到攻击.stop()
			动画_受到攻击.play("Got_Damaged")
		hitpoints = new_hitpoints
		if hitpoints <= 0:
			gameover.gameover()




# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity: float = ProjectSettings.get_setting("physics/3d/default_gravity")
var mouse_motion: Vector2 = Vector2.ZERO

func _ready() -> void:
	Input.mouse_mode = Input.MOUSE_MODE_CAPTURED #设置鼠标为捕获模式 鼠标被隐藏在屏幕中心
func _physics_process(delta: float) -> void:
	handle_camera_rotation()
	# Add the gravity.
	if not is_on_floor():
		if velocity.y >= 0:
			velocity.y -= gravity * delta
		else:
			velocity.y -= gravity * fall_multiple * delta
	# Handle jump.
	if Input.is_action_just_pressed("jump") and is_on_floor():
		velocity.y = sqrt(jump_height * 2.0 * gravity) # 上抛运动到达最高需要的速度
	if Input.is_action_pressed("move_fast"):
		SPEED = 20
	else :
		SPEED = 5
		

	# Get the input direction and handle the movement/deceleration.
	# As good practice, you should replace UI actions with custom gameplay actions.
	var input_dir := Input.get_vector("move_left", "move_right", "move_forward", "move_back")
	var direction := (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
	if direction:
		velocity.x = direction.x * SPEED
		velocity.z = direction.z * SPEED
	else:
		velocity.x = move_toward(velocity.x, 0, SPEED)
		velocity.z = move_toward(velocity.z, 0, SPEED)
		
	move_and_slide()
#覆盖输入监听输入函数
func _input(event: InputEvent) -> void:
	if event is InputEventMouseMotion:
		mouse_motion = -event.relative * 0.001 * mouse_sensitivity_multiple #鼠标当前位置与前一帧的相对位置,从结束位置指向前一帧位置,所以用"-"
	if event.is_action_pressed("ui_cancel"):
		Input.mouse_mode = Input.MOUSE_MODE_VISIBLE
# 实现视角旋转函数
func _unhandled_input(event: InputEvent,) -> void:
	if event.is_action_pressed("aim"):
		aim.emit(multiple)
		mouse_sensitivity_multiple *= 0.5
		print(mouse_sensitivity_multiple)
	if event.is_action_released("aim"):
		mouse_sensitivity_multiple = 1.0
		print(mouse_sensitivity_multiple)
		Input
		
func handle_camera_rotation() -> void:
	if Input.mouse_mode == Input.MOUSE_MODE_CAPTURED:
		rotate_y(mouse_motion.x)
		camera_pivot.rotate_x(mouse_motion.y)
		camera_pivot.rotation_degrees.x = clampf(
			camera_pivot.rotation_degrees.x,-90,90
		)
		mouse_motion = Vector2.ZERO
